package core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import repository.Repository;

public class JitConfig {
	/**
	 * Init user info for repository.
	 * @param mode
	 * @param object
	 * @param name
	 * @throws IOException
	 */
    public static void config(String mode, String object, String name) throws IOException {
    	File config = null;
    	if(mode.equals("--global")){
    		config = new File("." + File.separator + "src" + File.separator + ".jitconfig");
    	}
    	else if(mode.equals("--local")) {
    		config = new File(Repository.getGitDir() + File.separator + "config");
    	}
    	
        if(config.exists()){
			try {
				FileInputStream is = new FileInputStream(config);
		        BufferedReader br = new BufferedReader(new InputStreamReader(is));
		        String line = br.readLine();
		        String content = "";
		        while (line != null){
		        	if(!line.contains(object)){
		        		content += line + "\n";
		        	}
		        	else {
		        		content += object + " : " + name + "\n";
		        	}
	                line = br.readLine();
	            }
		        br.close();
				FileWriter fw = new FileWriter(config, false);
				fw.write(content);
				fw.flush();
				fw.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(object + " has been set successfully.");
        }
        else {
        	FileWriter fileWriter = new FileWriter(config);
        	String content = object + " : " + name + "\n";
            fileWriter.write(content);
            fileWriter.close();
        }
    }
}